package example.simple_mindmap.service;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import example.simple_mindmap.common.config.FileProperties;
import example.simple_mindmap.common.config.RedisProperties;
import example.simple_mindmap.common.domain.dto.UserDTO;
import example.simple_mindmap.common.domain.po.AppException;
import example.simple_mindmap.common.domain.po.Result;
import example.simple_mindmap.common.enums.ResultCode;
import example.simple_mindmap.common.utils.*;
import example.simple_mindmap.common.utils.cacheUtil.CacheClient;
import example.simple_mindmap.config.UserProperties;
import example.simple_mindmap.domain.dto.LoginFormDTO;
import example.simple_mindmap.domain.po.SignUpKey;
import example.simple_mindmap.domain.po.User;
import example.simple_mindmap.mapper.SignUpKeyMapper;
import example.simple_mindmap.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.service
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-07  14:24
 * @Version : 1.0
 * @Description : TODO
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    private final StringRedisTemplate stringRedisTemplate;
    private final CacheClient cacheClient;
    private final SignUpKeyMapper signUpKeyMapper;
    private final UserMapper userMapper;
    private final RedisProperties redisProperties;
    private final UserProperties userProperties;
    private final FileProperties imageProperties;
    private final RedissonClient redissonClient;


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 登录检验
     * @Describe: TODO
     * @modifier: [public] [实例方法]
    **/

    public Result login(LoginFormDTO loginFormDTO) {
        //检验账号和密码
        String username = loginFormDTO.getUsername();
        String password = loginFormDTO.getPassword();
        if(RegexUtil.isUsernameInvalid(username) || RegexUtil.isPasswordInvalid(password))
            return Result.failed(ResultCode.FAILED_LOGIN);
        //redisson的读锁

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(redisProperties.lock_user+username);
        RLock readLock = readWriteLock.readLock();
        User user;


        try {
            readLock.lock();
            //检验用户是否存在
            user = query().eq("username",username).one();

            if(user == null)
                return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            //检验密码是否正确

            if(!MD5Util.verifyPassword(password,user.getPassword()))
                return Result.failed(ResultCode.FAILED_LOGIN);

        } finally {
            readLock.unlock();
        }

        //检验通过后，将用户信息放到DTO
        //将DTO转成hashmap
//        Map<String, Object> userMap = BeanUtil.beanToMap(user, new HashMap<>(),
//                CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        //生成Token
        String token = UUIDUtil.UUID_32();
        String key = redisProperties.session_user_pre + token;
        //保存会话到redis
        stringRedisTemplate.opsForValue().set(key, String.valueOf(user.getId()));
        stringRedisTemplate.expire(key,redisProperties.session_user_save_time, TimeUnit.MINUTES);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        userDTO.setToken(token);
        //返回给前端
        return Result.success(userDTO);
    }

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 注册功能
     * @Describe: TODO
     * @modifier: [public] [实例方法]
     **/
    public Result signUp(LoginFormDTO loginFormDTO){
        //账号密码
        String username = loginFormDTO.getUsername();
        String password = loginFormDTO.getPassword();
        String signUpKey= loginFormDTO.getSignUpKey();
        if(RegexUtil.isUsernameInvalid(username) || RegexUtil.isPasswordInvalid(password) || RegexUtil.isUUIDInvalid(signUpKey))
            return Result.failed(ResultCode.FAILED_LOGIN);

        //密钥key检验
        SignUpKey key = signUpKeyMapper.selectOneByKey(signUpKey);
        if(key == null || key.getUid()>=0){
            return Result.failed(ResultCode.FAILED_LOGIN_KEY);
        }

        //用户名检验
        User cur = query().eq("username",username).one();
        if(cur != null){
            return Result.failed(ResultCode.FAILED_USER_EXISTS);
        }

        //密码加密
        String Md5Password = MD5Util.md5Salt(password, UUIDUtil.UUID_32());
        //保存用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        initialize(user);
        saveOrUpdate(user);
        //绑定密钥key
        key.setUid(lambdaQuery().eq(User::getUsername,user.getUsername()).one().getId());
        signUpKeyMapper.updateKey(key);
        //返回结果给前端
        return Result.success();
    }




    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 获取用户信息
     * @Describe: TODO
     * @modifier: [public] [实例方法]
     **/
    public Result<UserDTO> userInfo(Long id){
        //redisson的读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(redisProperties.lock_user+id);
        RLock readLock = readWriteLock.readLock();
        UserDTO user = null;
        try {
            readLock.lock();
            //1.未传入用户id时，获取当前登录用户对象
            if(id == null){
                user = cacheClient.queryPassThrough(redisProperties.cache_user_pre+SessionHolder.getUser(),
                        SessionHolder.getUser(),UserDTO.class,redisProperties.session_user_save_time,TimeUnit.MINUTES,this::getUser);
                //2.传入用户id时，获取此id的用户对象
            }else if(DataUtil.isNaturalNumInvalid(id)){
                log.error("用户id不合法");
                return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
            }else {
                user = cacheClient.queryPassThrough(redisProperties.cache_user_pre+id,
                        id,UserDTO.class,redisProperties.session_user_save_time,TimeUnit.MINUTES,this::getUser);
            }
            if(user == null){
                return Result.failed(ResultCode.FAILED);
            }
        } finally {
            readLock.unlock();
        }
        //3.返回用户对象给前端（
        return Result.success(user);
    }

    /* ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 从数据库获取用户的DTO
    **/
    private UserDTO getUser(Long uid){
        User user = getById(uid);
        if(user == null){
            return null;
        }
        return BeanUtil.copyProperties(user,UserDTO.class);
    }


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 登出
    **/
    public Result logout(){
        stringRedisTemplate.delete(redisProperties.session_user_pre+SessionHolder.getToken());
        return Result.success();
    }


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 修改用户信息
    **/
    public Result modifyInfo(UserDTO userDTO){
        if(userDTO == null){
            log.warn("修改用户信息时，传入参数无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //redisson的写锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(redisProperties.lock_user+SessionHolder.getUser());
        RLock writeLock = readWriteLock.writeLock();
        User user;
        try {
            writeLock.lock();
            UserDTO srcUserDTO = cacheClient.queryPassThrough(redisProperties.cache_user_pre+SessionHolder.getUser(),
                    SessionHolder.getUser(),UserDTO.class,redisProperties.session_user_save_time,TimeUnit.MINUTES,this::getUser);


            srcUserDTO.setAll(userDTO);

            user = BeanUtil.copyProperties(srcUserDTO, User.class);
            initialize(user);
            userMapper.updateUser(user);

            //删除缓存
            cacheClient.removeCache(redisProperties.cache_user_pre+ SessionHolder.getUser());
        } finally {
            writeLock.unlock();
        }
        return Result.success(BeanUtil.copyProperties(user,UserDTO.class));
    }

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 修改密码
     * @Describe: TODO
     * @modifier: [public] [实例方法]
     **/
    public Result modeifyPassword(String oldPassword,String newPassword){
        if(RegexUtil.isPasswordInvalid(oldPassword) || RegexUtil.isPasswordInvalid(newPassword)){
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        User user = getById(SessionHolder.getUser()) ;
        //redisson的写锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(redisProperties.lock_user+user.getUsername());
        RLock writeLock = readWriteLock.writeLock();
        try {
            writeLock.lock();
            if(!MD5Util.verifyPassword(oldPassword,user.getPassword())){
                return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
            }

            user.setPassword(MD5Util.md5Salt(newPassword,UUIDUtil.UUID_32()));
            user.setUpdateTime(new Date());

            saveOrUpdate(user);
        } finally {
            writeLock.unlock();
        }
        return Result.success();
    }


    public Result sendImage(MultipartFile image){
        //redisson的写锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(redisProperties.lock_user+SessionHolder.getUser());
        RLock writeLock = readWriteLock.writeLock();
        User user;
        try {
            writeLock.lock();
            UserDTO userDTO = cacheClient.queryPassThrough(redisProperties.cache_user_pre+SessionHolder.getUser(),
                    SessionHolder.getUser(),UserDTO.class,redisProperties.session_user_save_time,TimeUnit.MINUTES,this::getUser);

            //1.删除之前头像
            if(!userDTO.getAvatarUrl().equals("/image/avatar01.jpeg")){
                File oldFile = new File(imageProperties.save_file_url +userDTO.getAvatarUrl());
                if(oldFile.exists()){
                    oldFile.delete();
                }
            }

            //2.获取文件后置
            String imageName = image.getOriginalFilename();
            String[] strs = imageName.split("\\.");
            String affix = strs[strs.length-1];

            //3.确定图片存储位置
            String filePath = "/image/avatar/"+UUIDUtil.UUID_36()+"."+affix;
            File file = new File(imageProperties.save_file_url +filePath);

            //4.保存图片
            try(OutputStream outputStream = new FileOutputStream(file)){
                byte[] bytes = image.getBytes();
                outputStream.write(bytes);
                outputStream.flush();
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //保存用户信息
            user = BeanUtil.copyProperties(userDTO, User.class);
            user.setAvatarUrl(filePath);
            initialize(user);
            userMapper.updateUser(user);

            //删除缓存
            cacheClient.removeCache(redisProperties.cache_user_pre+ SessionHolder.getUser());
        } finally {
            writeLock.unlock();
        }
        return Result.success(BeanUtil.copyProperties(user,UserDTO.class));
    }


    private void initialize(User user){
        if(user.getUsername() == null){
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new AppException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if(user.getPassword() == null){
            user.setPassword("无");
        }
        if(user.getNickname() == null){
            user.setNickname("未命名");
        }
        if(user.getPhoneNum() == null){
            user.setPhoneNum("无");
        }
        if(user.getEmail() == null){
            user.setEmail("无");
        }
        if(user.getGender() == null){
            user.setGender(Byte.valueOf("0"));
        }
        if(user.getAvatarUrl() == null){
            user.setAvatarUrl(userProperties.avatar_url);
        }
        if(user.getRemark() == null){
            user.setRemark("这是一个神秘的人，什么介绍都没有");
        }
        if(user.getState() == null){
            user.setState(Byte.valueOf("0"));
        }
        if(user.getCreateTime() == null){
            user.setCreateTime(new Date());
        }
        if(user.getUpdateTime() == null){
            user.setUpdateTime(new Date());
        }
    }



}
